<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('role.roleInfo')"
    custom-class="dialog-min-width"
    :before-close="handleClose"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="formEdit" :rules="rules" label-width="120px">
      <el-row>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('role.roleName')" prop="roleName">
            <el-input v-model="formEdit.roleName" maxlength="64">
              <template #suffix>
                <el-icon> </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('role.roleCode')" prop="roleCode">
            <el-input v-model="formEdit.roleCode" maxlength="64">
              <template #suffix>
                <el-icon> </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('role.orderIndex')" prop="orderIndex">
            <el-input v-model="formEdit.orderIndex" maxlength="8">
              <template #suffix>
                <el-icon> </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="24" :xs="24">
          <el-form-item :label="t('role.category')" prop="category">
            <el-input v-model="formEdit.category" maxlength="32">
              <template #suffix>
                <el-icon> </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('role.description')">
            <el-input
              v-model="formEdit.description"
              maxlength="64"
              type="textarea"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('role.authorizedResources')">
            <el-tree
              v-if="state.dialogFormVisible"
              ref="treeResourceRef"
              :data="state.treeData"
              show-checkbox
              node-key="resourceId"
              :default-checked-keys="state.treeCheckedIds"
              :props="treeProps"
              class="fix-el-tree"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import utils from "../../../utils/utils";
import apiRole from "../api/role";
import apiResource from "../api/resource";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
const formRef = ref();
const treeResourceRef = ref();

const treeProps = {
  label: "resourceName",
  children: "children",
  isLeaf: "leaf",
};

const state = reactive({
  dialogFormVisible: false,
  treeData: <any>null,
  treeCheckedIds: [],
});

const formEditOriginal = () => {
  return {
    roleId: "",
    orderIndex: 0,
    roleName: "",
    roleCode: "",
    category: "",
    description: "",
    resourceIds: Array<string>(),
  };
};

const formEdit = reactive(formEditOriginal());

const rules = reactive({
  roleName: [
    { required: true, message: () => t("common.required"), trigger: "blur" },
  ],
  roleCode: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
  orderIndex: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
  category: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
});

const emit = defineEmits<{
  // true 表示提交成功
  (event: "on-submit-success", row: any): void;
}>();

// const lazyLoadNode = async (
//   node: Node,
//   resolve: (data: ResourceTreeNode[]) => void
// ) => {
//   if (node.level === 0) {
//     let treeData = await apiResource.loadChilds("0");
//     return resolve(treeData);
//   } else {
//     if (node.data.leaf) {
//       resolve([]);
//     }
//     let treeData = await apiResource.loadChilds(node.data.resourceId);
//     return resolve(treeData);
//   }
// };

const handleSubmit = async () => {
  // 处理业务逻辑，触发关闭事件
  await formRef.value.validate();

  let resourceIds = Array<string>();
  treeResourceRef.value.getCheckedNodes().forEach((m: any) => {
    resourceIds.push(m.resourceId);
  });
  formEdit.resourceIds = resourceIds;
  console.log("handleSubmit", formEdit.resourceIds);

  apiRole
    .updateRole(formEdit)
    .then((response: any) => {
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

const handleClose = (submit: boolean) => {
  state.dialogFormVisible = false;
};

const show = (row: any) => {
  // console.log(row);
  Object.assign(formEdit, formEditOriginal());
  if (row != undefined) {
    apiRole
      .getRole(row.roleId)
      .then((response: any) => {
        if (response.data.code == 200) {
          Object.assign(formEdit, response.data.data);
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });

    apiRole
      .queryRoleCheckResourceIds(row.roleId)
      .then((response: any) => {
        if (response.data.code == 200) {
          state.treeCheckedIds = response.data.data;

          apiResource
            .queryAllResource()
            .then((response: any) => {
              if (response.data.code == 200) {
                state.treeData = response.data.data;
                // Object.assign(state.treeData, response.data.data);
              }
            })
            .catch((err: any) => {
              utils.errorNotification(t("common.submitException"), err);
            });
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  }

  state.dialogFormVisible = true;
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

defineExpose({
  show,
});
</script>
<style>
/* fix 暂无数据时样式 */
.fix-el-tree .el-tree__empty-text {
  transform: inherit;
  top: inherit;
  width: 100px;
  text-align: left;
}
</style>
